<?php

namespace App\Http\Controllers\Ceb;

use App\Constants\UserFilterType;
use App\Models\Activity;
use App\Models\Channel;
use App\Models\ChannelProvider;
use App\Models\RewardPackage;
use App\Models\UserGroup;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Ceb\BaseController as Controller;
use Illuminate\Support\Facades\DB;

class ActivityController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $int_Page = $request->get('page',1);
        $int_PageSize = $request->get('page_size',10);
        $str_Keyword = $request->get('keyword','');
        if($str_Keyword){
            $obj_ActivityList = Activity::forPage($int_Page,$int_PageSize)
                ->where('name','like','%' . $str_Keyword . '%')
                ->get();
            $int_Count = Activity::where('name','like','%' . $str_Keyword . '%')->count();
        }else{
            $obj_ActivityList = Activity::forPage($int_Page,$int_PageSize)->get();
            $int_Count = Activity::count();
        }
        return $this->view('activity.index',[
            'count' => $int_Count,
            'size' => $int_PageSize,
            'page' => $int_Page,
            'list' => $obj_ActivityList,
            'keyword' => $str_Keyword
        ]);
    }

    public function getActivityListByPage(Request $request){
        $int_Page = $request->get('page',1);
        $int_PageSize = $request->get('page_size',10);
        $str_Keyword = $request->get('keyword',null);
        if($str_Keyword){
            $obj_ActivityList = Activity::forPage($int_Page,$int_PageSize)
                ->where('name','like','%' . $str_Keyword . '%')
                ->get();
            $int_Count = Activity::where('name','like','%' . $str_Keyword . '%')->count();
        }else{
            $obj_ActivityList = Activity::forPage($int_Page,$int_PageSize)->get();
            $int_Count = Activity::count();
        }
        return $this->view('activity.index',[
            'count' => $int_Count,
            'size' => $int_PageSize,
            'page' => $int_Page,
            'list' => $obj_ActivityList
        ]);
    }

    public function create(){
        $col_ChannelProvider = ChannelProvider::all(['id','name']);
        $col_Channel = Channel::all(['id','code','no','channel_provider_id']);
        $col_UserGroup = UserGroup::all(['id','name']);
        $arr_Behavior = [
            [
                'name' => '注册',
                'id' => 1
            ],
            [
                'name' => '登录',
                'id' => 2
            ],
            [
                'name' => '投资',
                'id' => 3
            ]
        ];
//        $col_Rewards = RewardPackage::all();
        return $this->view('activity.create',[
            'channel_provider_list' => $col_ChannelProvider,
            'channel_list' => $col_Channel,
            'group_list' => $col_UserGroup,
            'behavior_list' => $arr_Behavior
        ]);
    }

    public function store(Request $request){
        $this->validate($request,[
            'name' => 'required|string|max:256|min:1',
            'start_date' => 'required|date_format:Y-m-d',
            'end_date' => 'required|date_format:Y-m-d',
            'banner' => 'required|string',
            'rules' => 'string',
            'purpose' => 'string',
            'filter_type' => 'required|in:' . implode(',',[
                    UserFilterType::CHANNEL,
                    UserFilterType::USER_GROUP
                ]),
            'channel' => 'array|required_if:filter_type,' . UserFilterType::CHANNEL,
            'group' => 'array|required_if:filyer_type,' . UserFilterType::USER_GROUP,
            'ignore_user' => 'required|array',
            'rewards' => 'required|array'
        ]);
        $mod_Activity = new Activity();
        $mod_Activity->name = $request->name;
        $mod_Activity->start_time = strtotime($request->start_date);
        $mod_Activity->end_time = strtotime($request->end_date);
        $mod_Activity->banner = $request->banner;
        $mod_Activity->rules = $request->rules;
        $mod_Activity->filter_type = $request->filter_type;

        if($request->filter_type == UserFilterType::CHANNEL){
            $arr_ChannelId = $request->channel;
            $col_Channel = Channel::whereIn('id',$arr_ChannelId)
                ->select(DB::raw('group_concat(concat(code,no)) as names'))
                ->first();
            $str_Filters = $col_Channel->names;
        }else{
            $arr_GroupId = $request->group;
            $col_Group = UserGroup::whereIn('id',$arr_GroupId)
                ->select(DB::raw('group_concat(name) as names'))
                ->first();
            $str_Filters = $col_Group->names;
        }
        $mod_Activity->user_filter = $str_Filters;
        $mod_Activity->ignores = implode(',',$request->ignore_user);
        $arr_RewardId = [];

        foreach($request->rewards as $str_Reward){
            $arr_Reward = explode(',',$str_Reward);
            $arr_RewardId[$arr_Reward[0]] = [
                'behavior' => $arr_Reward[1]
            ];
        }
        $col_Reward = RewardPackage::whereIn('id',array_keys($arr_RewardId))
            ->select(DB::raw('group_concat(`name`) as names'))
            ->first();
        $mod_Activity->rewards = $col_Reward->names;
        DB::beginTransaction();
        try{
            if(!$mod_Activity->save()){
                throw new \Exception('创建活动失败!');
            }
            if($mod_Activity->filter_type == UserFilterType::CHANNEL){
                $mod_Activity->channels()->sync($request->channel);
            }else if($mod_Activity->filter_type == UserFilterType::USER_GROUP){
                $mod_Activity->groups()->sync($request->group);
            }
            $mod_Activity->packages()->sync($arr_RewardId);
        }catch (\Exception $e){
            DB::rollback();
            return $e;
        }
        DB::commit();
        return redirect('/ceb/activities/index');

    }

    public function delete(Request $request){
        $int_ActivityId = $request->get('id');
        $mod_Activity = Activity::find($int_ActivityId);
        if(!$mod_Activity){
            return new \Exception('活动不存在');
        }
        if($mod_Activity->status != 0){
            return new \Exception('无法删除已审核的活动!');
        }
        if(!$mod_Activity->delete()){
            return new \Exception('删除失败!');
        }
        return redirect()->back();
    }

    public function check(Request $request){
        $int_Activity = $request->get('id');
        $mod_Activity = Activity::find($int_Activity);
        if(!$mod_Activity){
            return new \Exception('活动不存在');
        }
        if($mod_Activity->status != 0 ){
            return new \Exception('活动已通过审核');
        }

        $col_ChannelProvider = ChannelProvider::all(['id','name']);
        $col_Channel = Channel::all(['id','code','no','channel_provider_id']);
        $col_UserGroup = UserGroup::all(['id','name']);
        $arr_Behavior = [
            [
                'name' => '注册',
                'id' => 1
            ],
            [
                'name' => '登录',
                'id' => 2
            ],
            [
                'name' => '投资',
                'id' => 3
            ]
        ];
        $map_CheckStatus = config('activity-check');
        return $this->view('activity.check',[
            'channel_provider_list' => $col_ChannelProvider,
            'channel_list' => $col_Channel,
            'group_list' => $col_UserGroup,
            'behavior_list' => $arr_Behavior,
            'activity' => $mod_Activity,
            'check_status' => $map_CheckStatus
        ]);
    }

    public function doCheck(Request $request){
        $this->validate($request,[
            'id' => 'required|int|exists:activities',
            'name' => 'required|string|max:256|min:1',
            'start_date' => 'required|date_format:Y-m-d',
            'end_date' => 'required|date_format:Y-m-d',
            'banner' => 'required|string',
            'rules' => 'string',
            'purpose' => 'string',
            'filter_type' => 'required|in:' . implode(',',[
                    UserFilterType::CHANNEL,
                    UserFilterType::USER_GROUP
                ]),
            'channel' => 'array|required_if:filter_type,' . UserFilterType::CHANNEL,
            'group' => 'array|required_if:filyer_type,' . UserFilterType::USER_GROUP,
            'ignore_user' => 'required|array',
            'rewards' => 'required|array'
        ]);
        $int_ActivityId = $request->get('id');
        $mod_Activity = Activity::find($int_ActivityId);
        if($mod_Activity->status != 0 ){
            return new \Exception('活动已通过审核');
        }
        $data = [
            'name' => $request->name,
            'start_time' => strtotime($request->start_date),
            'end_time' => strtotime($request->end_date)
        ];
        $mod_Activity->name = $request->name;
        $mod_Activity->start_time = strtotime($request->start_date);
        $mod_Activity->end_time = strtotime($request->end_date);
        $mod_Activity->banner = $request->banner;
        $mod_Activity->rules = $request->rules;
        $mod_Activity->filter_type = $request->filter_type;

        if($request->filter_type == UserFilterType::CHANNEL){
            $arr_ChannelId = $request->channel;
            $col_Channel = Channel::whereIn('id',$arr_ChannelId)
                ->select(DB::raw('group_concat(concat(code,no)) as names'))
                ->first();
            $str_Filters = $col_Channel->names;
        }else{
            $arr_GroupId = $request->group;
            $col_Group = UserGroup::whereIn('id',$arr_GroupId)
                ->select(DB::raw('group_concat(name) as names'))
                ->first();
            $str_Filters = $col_Group->names;
        }
        $mod_Activity->user_filter = $str_Filters;
        $mod_Activity->ignores = implode(',',$request->ignore_user);
        $arr_RewardId = [];

        foreach($request->rewards as $str_Reward){
            $arr_Reward = explode(',',$str_Reward);
            $arr_RewardId[$arr_Reward[0]] = [
                'behavior' => $arr_Reward[1]
            ];
        }
        $col_Reward = RewardPackage::whereIn('id',array_keys($arr_RewardId))
            ->select(DB::raw('group_concat(`name`) as names'))
            ->first();
        $mod_Activity->rewards = $col_Reward->names;
        DB::beginTransaction();
        try{
            if(!$mod_Activity->save()){
                throw new \Exception('创建活动失败!');
            }
            if($mod_Activity->filter_type == UserFilterType::CHANNEL){
                $mod_Activity->channels()->sync($request->channel);
            }else if($mod_Activity->filter_type == UserFilterType::USER_GROUP){
                $mod_Activity->groups()->sync($request->group);
            }
            $mod_Activity->packages()->sync($arr_RewardId);
        }catch (\Exception $e){
            DB::rollback();
            return $e;
        }
        DB::commit();
        return redirect('/ceb/activities/index');
    }

    public function show(Request $request){
        $int_ActivityId = $request->get('id');
        $mod_Activity = Activity::find($int_ActivityId);
        if(!$mod_Activity){
            return new \Exception('活动不存在');
        }
        if($mod_Activity->status != 0 ){
            return new \Exception('活动已通过审核');
        }
    }
}





